var text = ``;
window.onload = function () {
  chrome.storage.local.get("isRunning", (data) => {
    if (data.isRunning) {
      observeChatBox();
    }
  });
  console.log("chatLoad");
  chrome.storage.local.get("text", (data) => {
    console.log(data, "data");
    if (data.text) {
      text = data.text;
    }
  });
};

// chrome.storage.onChanged.addListener((changes, areaName) => {
//   // if (changes.text && changes.text.newValue) {
//   //   console.log("改变打招呼文本");
//   //   text = Math.floor(changes.text.newValue);
//   // }
// });

function observeChatBox() {
  const observer = new MutationObserver(() => {
    const chatInput = document.querySelector(".chat-input"); // 修改为实际 class
    const sendButton = document.querySelector(".btn-v2.btn-sure-v2.btn-send"); // 修改为实际 class

    if (chatInput && sendButton) {
      setTimeout(() => {
        chatInput.innerHTML = text;
        setTimeout(() => {
          sendButton.click();
          setTimeout(() => {
            // 关闭当前聊天窗口;
            chrome.storage.local.set({ runningOneStatus: "done" });
            // window.close();
            chrome.runtime.sendMessage({ action: "close_current_tab" });
          }, 500);
        }, 500);
      }, 500);
      observer.disconnect(); // 只执行一次，避免重复触发
    }
  });

  observer.observe(document.body, { childList: true, subtree: true });
}
